/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

import { FileSet } from '@ohos/hvigor';
import fse from 'fs-extra';
import path from 'path';

import { BuildDirConst } from '../../const/build-directory-const.js';
import { TaskNames } from '../common/task-names.js';
import { TargetTaskService } from '../service/target-task-service.js';
import { OhosHapTask } from '../task/ohos-hap-task.js';
import { PreviewHookCompileResource } from '../hook/preview-hook-compile-resource.js';
import CommonTask = TaskNames.CommonTask;

/**
 * 处理资源增量编译时，restool不复制resources目录，手动copy profile路由配置文件
 * 此任务要处理好增量，因为会写入res目录，输出会影响以res目录作为输入的任务。
 */
export class CopyPreviewProfile extends OhosHapTask {
  private readonly profilePath: string | undefined = undefined;
  private readonly targetProfilePath: string | undefined = undefined;

  constructor(taskService: TargetTaskService) {
    super(taskService, CommonTask.COPY_PREVIEWER_PROFILE);
    this.profilePath = path.resolve(
      this.targetData.getModuleModel().getSourceRootByTargetName(this.targetData.getModuleModel().getName()),
      BuildDirConst.RESTOOL_BUILD_RESOURCES,
      BuildDirConst.BASE,
      BuildDirConst.PROFILE,
    );
    this.targetProfilePath = path.resolve(
      this.targetData.getPathInfo().getIntermediatesRes(),
      BuildDirConst.RESTOOL_BUILD_RESOURCES,
      BuildDirConst.BASE,
      BuildDirConst.PROFILE,
    );
  }

  initTaskDepends(): void {
    this.declareDepends(PreviewHookCompileResource.name);
  }

  declareInputFiles(): FileSet {
    const inputFiles = new FileSet();
    if (this.profilePath && fse.existsSync(this.profilePath)) {
      inputFiles.addEntry(this.profilePath);
    }
    return inputFiles;
  }

  declareOutputFiles(): FileSet {
    const outputFiles = new FileSet();
    if (this.targetProfilePath) {
      outputFiles.addEntry(this.targetProfilePath);
    }
    return outputFiles;
  }

  protected doTaskAction(): void {
    // 资源文件夹下的profile目录,profile路径存在才需要复制
    if (this.profilePath === undefined || !fse.existsSync(this.profilePath)) {
      return;
    }

    if (this.targetProfilePath) {
      fse.ensureDirSync(this.targetProfilePath);
      fse.copySync(this.profilePath, this.targetProfilePath, { recursive: true });
    }
  }
}
